//
//  eBookIndexer.m
//  Capstone Project
//
//  Created by Brian Gilreath on 12/7/10.
//  Copyright 2010 GilreathCapstone. All rights reserved.
//

#import "OH_FeBookIndexer.h"


@implementation OH_FeBookIndexer

@synthesize OH_FeBookSet, OH_FPlistFileURL, bundle;

-(OH_FeBookIndexer*)init{
	bundle = [NSBundle mainBundle];
	OH_FPlistFileURL = [[NSURL alloc] initFileURLWithPath:[bundle pathForResource:@"OH_FeBookIndex" ofType:@"plist"]];
	//[[NSURL alloc] initWithString:@"OH_FeBookIndex.plist" relativeToURL:[bundle bundleURL]];
	if (OH_FPlistFileURL == nil) {
		return nil;
	}
	if (self = [super init]) {
		[self OH_FLoadIndex];
		if([self OH_FIndexCheck] == FALSE){
			NSLog(@"Rebuilding eBook Index");
			[self OH_FRebuildIndex];
		}
	}
	return self;
}

-(void)OH_FLoadIndex{
	OH_FeBookSet = [[NSMutableArray alloc] initWithContentsOfURL:OH_FPlistFileURL];
}

-(void)OH_FRebuildIndex{
	OH_FeBookSet = [[NSMutableArray alloc] init];
	NSArray *eBooks = [bundle pathsForResourcesOfType:@"epub" inDirectory:nil];
	[OH_FeBookSet addObjectsFromArray:eBooks];
	BOOL result = [OH_FeBookSet writeToURL:OH_FPlistFileURL atomically:YES];
	if (result == FALSE) {
		NSLog(@"Unable to save index closing... Exit code -1");
		exit(-1);
	}
//	NSString *filePath = @"/System/Library/CoreServices/SystemVersion.plist";
//	NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
//	
//	[plistDict setValue:@"1.1.1" forKey:@"ProductVersion"];
//	[plistDict writeToFile:filePath atomically: YES];
}

-(BOOL)OH_FIndexCheck{
	if (OH_FeBookSet == NULL) {
		return FALSE;
	}
	// first build an index of all our current epub books
	NSArray *epubBooks = [bundle pathsForResourcesOfType:@"epub" inDirectory:nil];
	if ([epubBooks count] < [OH_FeBookSet count]) {
		return FALSE;
	}
	if (![OH_FeBookSet isEqualToArray:epubBooks]) {
		return FALSE;
	}
	
	return TRUE;
}

-(void)OH_FUnpackAllFiles{
	
}

-(void)OH_FPackAllFiles{
	
}

-(int)OH_FPackFile:(NSURL *)path :(NSURL *)toHere{
	return 0;
}

-(int)OH_FUnpackFile:(NSURL *)path :(NSURL *)toHere{
	return 1;
}

-(void)dealloc{
	[bundle release];
	[super dealloc];
}

@end
